/**
 * @Project Name :  als-rpc
 * @Package Name :  com.alvis.registercenter
 * @Description :  TODO
 * @author :  Alvis
 * @Creation Date:  2018-07-05 11:57 AM
 * @ModificationHistory Who    When    What
 * --------  ---------  --------------------------
 */
package com.alvis.registry.zookeeper;

import com.alvis.config.RpcConfig;
import com.alvis.utilities.Component;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author :  Alvis
 * @Description :  TODO
 * @Creation Date:  2018-07-05 11:57 AM
 */
public class RegisterManager implements Component {
    private final static Logger logger = LoggerFactory.getLogger(RegisterManager.class);
    private final static int SESSION_OUTTIME = 5000;

    private CuratorFramework curatorFramework;
    private static ServiceNode zkServiceNode;

    @Override
    public void start() {
        zkInit();
        zkServiceNode = new ServiceNode(curatorFramework);
        //zkServiceNode.start();
        serviceToZooKeeper();
    }

    @Override
    public void stop() {
        zkServiceNode.stop();
        curatorFramework.close();
    }

    public static ServiceNode getZkServiceNode() {
        return zkServiceNode;
    }


    private void zkInit() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(RpcConfig.getZookeeper())
                .sessionTimeoutMs(SESSION_OUTTIME)
                .retryPolicy(retryPolicy)
                .build();
        curatorFramework.start();
    }


    private void serviceToZooKeeper() {
        ServiceContainer.getServiceNames().forEach(s -> {
            logger.info(" rpc service register to zookeeper : " + s);
            zkServiceNode.addNode(s);
        });
    }


}
